package cluster

import (
	"context"
	"krm-backend/config"
	"krm-backend/utils"
	"krm-backend/utils/logs"
	"net/http"

	"github.com/gin-gonic/gin"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// method： 参数 更新或创建集群
func addOrUpdate(r *gin.Context, method string) {
	var arg string
	if method == "Create" {
		arg = "添加"
	} else {
		arg = "更新"
	}
	clusterConfig := ClusterConfig{} // 声明集群配置
	returnData := config.NewReturnData()
	if err := r.ShouldBindBodyWithJSON(&clusterConfig); err != nil {
		msg := "添加集群配置信息不完整：" + err.Error()
		returnData.Status = 400
		returnData.Message = msg
		r.JSON(200, returnData)
		return
	}
	clusterStatus, err := clusterConfig.getClusterStatus() // 判断集群是否正常
	if err != nil {
		msg := "无法获取集群信息：" + err.Error()
		returnData.Status = 400
		returnData.Message = msg
		r.JSON(http.StatusOK, returnData)
		logs.Error(map[string]interface{}{"error": err.Error()}, arg+"添加集群失败,无法获取集群信息")
		return
	}

	logs.Info(map[string]interface{}{"集群名称": clusterConfig.DisplayName, "集群ID": clusterConfig.Id}, "开始"+arg+"集群")
	var clusterConfigSecrte corev1.Secret // 声明集群secret
	clusterConfigSecrte.Name = clusterConfig.Id
	clusterConfigSecrte.Labels = make(map[string]string)
	clusterConfigSecrte.Labels[config.ClusterConfigSecretLabelKey] = config.ClusterConfigSecretLabelValue
	clusterConfigSecrte.Annotations = make(map[string]string)
	// clusterConfigSecrte.Annotations["displayName"] = clusterConfig.DisplayName
	// clusterConfigSecrte.Annotations["city"] = clusterConfig.City
	// clusterConfigSecrte.Annotations["district"] = clusterConfig.District
	m := utils.StructToMap(clusterStatus) // 结构体转map
	clusterConfigSecrte.Annotations = m
	clusterConfigSecrte.StringData = make(map[string]string) // StringData方法自动加密data数据
	clusterConfigSecrte.StringData["kubeconfig"] = clusterConfig.KubeConfig
	// 创建secret
	if method == "Create" {
		_, err = config.InClusterClientSet.CoreV1().Secrets(config.MetadataNamespace).Create(context.TODO(), &clusterConfigSecrte, metav1.CreateOptions{})
	} else {
		_, err = config.InClusterClientSet.CoreV1().Secrets(config.MetadataNamespace).Update(context.TODO(), &clusterConfigSecrte, metav1.UpdateOptions{})
	}
	if err != nil { // 创建失败
		logs.Error(map[string]interface{}{"集群ID": clusterConfig.Id, "集群名称": clusterConfig.DisplayName, "msg": err.Error()}, "集群创建失败")
		msg := "集群" + arg + "失败：" + err.Error() // 返回给前端
		returnData.Status = 400
		returnData.Message = msg
		r.JSON(200, returnData)
		return
	} else {
		config.ClusterkubeConfig[clusterConfig.Id] = clusterConfig.KubeConfig //往clusterConfig中添加集群信息
		logs.Info(map[string]interface{}{"集群ID": clusterConfig.Id, "集群名称": clusterConfig.DisplayName}, "集群"+arg+"成功")
		returnData.Status = 200
		returnData.Message = "集群" + arg + "成功"
		r.JSON(200, returnData)
		return
	}
}
